import type { Result } from '@/request'
import { mergeRecursive } from '@/utils/obj'
interface TableOption {
  isPage: boolean // 是否分页
  pageNum: number // 当前页
  pageSize: number // 每页条数
  queryParams: Record<string, any> // 查询参数
  queryFn?: <T = any>(data: any) => Promise<Result<T>> // 查询方法
  delFn?: () => Promise<Result<null>> // 删除方法
}

function useTable<T>(customOption: Partial<TableOption>) {
  const defaultOption = <TableOption>{
    isPage: true,
    pageNum: 1,
    pageSize: 20,
    queryParams: {}
  }

  const list = ref<T>(<T>[])

  const option = ref(mergeRecursive(defaultOption, customOption))
  // 查询
  const query = () => {
    const { queryParams, pageNum, pageSize, isPage, queryFn } = option.value
    if (!queryFn) return

    const params = isPage ? { ...queryParams, pageNum, pageSize } : queryParams
    queryFn(params).then(res => {
      list.value = res.data
    })
  }

  // 重置查询
  const resetQuery = () => {
    option.value.pageNum = 1
    query()
  }

  // 分页切换
  const pagingChange = (pageNum: number) => {
    option.value.pageNum = pageNum
    query()
  }

  return {
    query,
    resetQuery,
    pagingChange,
    list,
    pageNum: option.value.pageNum,
    pageSize: option.value.pageSize,
    queryParams: option.value.queryParams
  }
}

export default useTable
